package com.drw.start.oauth2.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

import com.drw.start.oauth2.service.IUsersService;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    //@Autowired
    //private DataSource dataSource;

    @Autowired
    private IUsersService usersService;

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Autowired
    public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
        //auth.inMemoryAuthentication().withUser("oauthuser").password("{noop}123").roles("OAUTH_DEMON");
        //auth.jdbcAuthentication().dataSource(dataSource);//如果使用默认的jdbcAuthen就不能使用自定义的UserDetailsService，否则会导致UserDetailsService无效，jdbcAuthen定义了很多默认的SQL语句
        auth.userDetailsService(usersService);//.passwordEncoder(passwordEncoder());
    }

   /*@Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //auth.userDetailsService(usersService).passwordEncoder(passwordEncoder());
        auth.userDetailsService(usersService).passwordEncoder(passwordEncoder());
    }*/

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf()
        .disable()
        .authorizeRequests()
        .antMatchers("/oauth/authorize")
        .authenticated()
        .and()
        .httpBasic();
    }

    /*@Bean
    public PasswordEncoder passwordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }*/

}
